package com.tnxst.phexamination.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bigkoo.pickerview.TimePickerView;
import com.google.android.material.button.MaterialButtonToggleGroup;
import com.jaygoo.selector.MultiSelectPopWindow;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tnxst.phexamination.R;
import com.tnxst.phexamination.activity.PackageServiceActivity;
import com.tnxst.phexamination.adapter.AddSignPackageAdapter;
import com.tnxst.phexamination.constant.HISConfig;
import com.tnxst.phexamination.databinding.SignDetailsBinding;
import com.tnxst.phexamination.dto.InhabitantDTO;
import com.tnxst.phexamination.dto.ServicePackageDTO;
import com.tnxst.phexamination.dto.SignDTO;
import com.tnxst.phexamination.dto.TeamDoctorDTO;
import com.tnxst.phexamination.public_health_docking_interface.FamilySignInterface;
import com.tnxst.phexamination.public_health_docking_interface.InhabitantInterface;
import com.tnxst.phexamination.public_health_docking_interface.TuberculosisInterface;
import com.tnxst.phexamination.utils.PictureFileUtil;
import com.tnxst.phexamination.utils.ReflectUtils;
import com.tnxst.phexamination.utils.StringUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.utils.WebServiceUtils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;
import com.tnxst.phexamination.vo.ContractVo;
import com.tnxst.phexamination.vo.SignVo;
import com.tnxst.phexamination.vo.TeamVo;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;
import org.apache.commons.collections.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import sun.misc.BASE64Encoder;

public class SignFragment extends Fragment {

    private SignDetailsBinding binding;

    private GlobalViewModel viewModel;

    private SignDTO signDTO;

    private InhabitantDTO inhabitantDTO;

    private Context context;

    private ArrayList<String> crowdLabel;

    private List<TeamDoctorDTO> teamDoctorDTOS;

    private TeamVo teamVo;

    private TeamDoctorDTO teamDoctorDTO;

    private List<ServicePackageDTO> servicePackageDTOS;

    private List<String> teamNames;

    private List<String> doctorNames;

    private AddSignPackageAdapter addSignPackageAdapter;

    private List<ServicePackageDTO> save;

    private String compressPath;

    private SignFragment(){

    }

    public static SignFragment newInstance(){
        return new SignFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.sign_details, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(requireActivity()).get(GlobalViewModel.class);
        context = getActivity();
        initData();
        initView();
    }

    private void initView() {
        if (inhabitantDTO != null){
            binding.editText2.setText(inhabitantDTO.getIDCARD());
            setInhabitantView();
        }


        binding.editText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String idCard = s.toString();
                if (idCard.length() >= 2 ){
                    List<InhabitantDTO> dtoList = viewModel.getInhabitantRepository().findByFieldList("NAME", idCard);
                    if (!CollectionUtils.isEmpty(dtoList)){
                        InhabitantDTO i = dtoList.get(0);
                        if (i != null){
                            inhabitantDTO = i;
//                            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                                TuberculosisInterface.verifyIsTbPatient(inhabitantDTO.getID(), new WebServiceUtils.Response<Map>() {
//                                    @Override
//                                    public void onSuccess(Map result) {
//                                        String is = result.get("Msg").toString();
//                                        if ("1.0".equals(is)){
//                                            return;
//                                        }
//                                    }
//                                    @Override
//                                    public void onError(String error) {
//                                        Utils.Toast(context,"验证患者是否失败！\n失败原因：" + error);
//                                    }
//                                });
//                            }
                            setInhabitantView();
                        }else {
                            clearInhabitantView();
                        }
                    }else {
                        clearInhabitantView();
                        inhabitantDTO = null;
                    }
                }
            }
        });

        if (StringUtils.isNotNull(viewModel.getUserInfo().getOrganizationName()))
            binding.textView189.setText(viewModel.getUserInfo().getOrganizationName());

        binding.editText63.setText(signDTO.getFEE());

        binding.editText60.setText(signDTO.getOTHEREMARK());

        binding.textView203.setText(signDTO.getSIGNDATE());

        binding.textView204.setText(signDTO.getSIGNDATE());

        binding.textView205.setText(signDTO.getENDTIME());

        binding.editText62.setText(signDTO.getPERSONNAME());

        if (StringUtils.isNull(signDTO.getCONTRACTID())){
            binding.textView203.setText(Utils.getTime(new Date()));
            binding.textView204.setText(Utils.getTime(new Date()));
            binding.textView205.setText(Utils.getTime(new Date()));
        }


        if (StringUtils.isNotNull(signDTO.getTAGS()))
            binding.textView194.setText(signDTO.getTAGS());

        if (StringUtils.isNull(binding.textView203.getText().toString()))
            binding.textView203.setText(Utils.getTime(new Date()));

        binding.textView203.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView203.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("签约时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });
        if (StringUtils.isNull(binding.textView204.getText().toString()))
            binding.textView204.setText(Utils.getTime(new Date()));
        binding.textView204.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView204.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("开始时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });
        if (StringUtils.isNull(binding.textView205.getText().toString()))
            binding.textView205.setText(Utils.getTime(new Date()));
        binding.textView205.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        if (date.before(Utils.setTime(binding.textView204.getText().toString()))) {
                            Utils.Toast(getActivity(), "所选时间不能小于开始时间！");
                            return;
                        }
                        binding.textView205.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("结束时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });


        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        binding.recycler.setLayoutManager(gridLayoutManager);
        binding.recycler.setAdapter(addSignPackageAdapter);
        addSignPackageAdapter.setOnclick(new AddSignPackageAdapter.Onclick() {
            @Override
            public void add(ServicePackageDTO signPackage) {
                save.add(signPackage);
                binding.editText63.setText(getTotal().toString());
            }

            @Override
            public void remove(ServicePackageDTO signPackage) {
                save.remove(signPackage);
                binding.editText63.setText(getTotal().toString());
            }
        });

        addSignPackageAdapter.setSignPackages(servicePackageDTOS);
        addSignPackageAdapter.setStatusTrue(save);
        addSignPackageAdapter.notifyDataSetChanged();

        binding.button7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideAddFragment();
            }
        });

        binding.textView207.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureFileUtil.showAlbum(SignFragment.this, PictureConfig.CHOOSE_REQUEST);
            }
        });

        binding.button8.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                //保存
                if (inhabitantDTO == null){
                    Utils.Toast(context,"请选择居民！");
                    return;
                }
                if (teamVo == null){
                    Utils.Toast(context,"请选择团队！");
                    return;
                }
                if (teamDoctorDTO == null){
                    Utils.Toast(context,"请选择团队医生！");
                    return;
                }
                saveData();
                signDTO.setUpload(false);
                signDTO.setCONTRACTID(UUID.randomUUID().toString());
                viewModel.getSignRepository().insert(signDTO);
//                if (StringUtils.isNotNull(signDTO.getCONTRACTID())){
//                    viewModel.getSignRepository().insert(signDTO);
//                }else {
//                    signDTO.setCONTRACTID("@"+ UUID.randomUUID().toString());
//                    viewModel.getSignRepository().insert(signDTO);
//                }
//                if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                    SignVo signVo = new SignVo();
//                    signVo.setContractID(signDTO.getCONTRACTID());
//                    signVo.setTags(signDTO.getTAGS());
//                    signVo.setTeamEmpId(signDTO.getTEAM_EMP_ID());
//                    signVo.setTeamID(signDTO.getTEAMID());
//                    signVo.setPERSON_ID(signDTO.getPERSONID());
//                    signVo.setSignDate(signDTO.getSIGNDATE());
//                    signVo.setOtheremark(signDTO.getOTHEREMARK());
//                    signVo.setEndTime(signDTO.getENDTIME());
//                    signVo.setStartTime(signDTO.getSTARTTIME());
//                    signVo.setContractServices(signDTO.getContractServices());
//                    signVo.setFee(signDTO.getFEE());
//                    signVo.setChannel(signDTO.getCHANNEL());
//                    signVo.setSignPerson(signDTO.getSIGNPERSON());
//
//                    if (StringUtils.isNotNull(signDTO.getATTACHFILE())){
//                        File file = new File(signDTO.getATTACHFILE());
//                        if (file.exists() && file.isFile()){
//                            try {
//                                FileInputStream inputFile = new FileInputStream(file);
//                                byte[] buffer = new byte[(int) file.length()];
//                                inputFile.read(buffer);
//                                inputFile.close();
//                                String encode = new BASE64Encoder().encode(buffer);
//                                String jg = file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".") + 1);
//                                switch (jg.toLowerCase()){
//                                    case "png":
//                                        encode = "data:image/png;base64," + encode;
//                                        break;
//                                    case "jpg":
//                                        encode = "data:image/jpg;base64," + encode;
//                                        break;
//                                    case "jpeg":
//                                        encode = "data:image/jpeg;base64," + encode;
//                                        break;
//                                    case "bmp":
//                                        encode = "data:image/bmp;base64," + encode;
//                                        break;
//                                    case "gif":
//                                        encode = "data:image/gif;base64," + encode;
//                                        break;
//                                }
//                                signVo.setAttachfile(encode);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//
//                    if (StringUtils.isNotNull(signVo.getContractID()) && signVo.getContractID().startsWith("@")){
//                        viewModel.getSignRepository().delete(signDTO);
//                        signVo.setContractID(null);
//                    }
//                    FamilySignInterface.familyDoctorSign(signVo, new WebServiceUtils.Response() {
//                        @Override
//                        public void onSuccess(Object result) {
//                            Utils.Toast(context,"保存或修改成功！");
//                            if (result.toString().contains("修改成功")){
//                                signDTO.setUpload(true);
//                                viewModel.getSignRepository().insert(signDTO);
//                                return;
//                            }
//                            signDTO.setCONTRACTID(result.toString().replace("[","").replace("]",""));
//                            signDTO.setUpload(true);
//                            viewModel.getSignRepository().insert(signDTO);
//                            hideAddFragment();
//                        }
//
//                        @Override
//                        public void onError(String error) {
//                            Utils.Toast(context,"保存或修改失败！\n" +error);
//                        }
//                    });
//                }
//                else {
//                    Utils.Toast(context,"保存本地成功！");
//                    hideAddFragment();
//                }

            }
        });

        binding.button10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //续约
//                if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                    if (StringUtils.isNotNull(signDTO.getCONTRACTID()) && !signDTO.getCONTRACTID().startsWith("@")){
//                        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
//                        View view = View.inflate(context, R.layout.contract, null);
//                        alertDialog
//                                .setView(view)
//                                .create();
//                        AlertDialog show = alertDialog.show();
//                        show.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//                        show.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//                        MaterialButtonToggleGroup group = show.findViewById(R.id.material);
//                        EditText text = show.findViewById(R.id.editText64);
//                        Button cancel = show.findViewById(R.id.button7);
//                        Button save = show.findViewById(R.id.button13);
//
//                        cancel.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                show.dismiss();
//                            }
//                        });
//
//                        save.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                int checkedButtonId = group.getCheckedButtonId();
//                                String reason = text.getText().toString();
//                                saveData();
//                                if (checkedButtonId == -1){
//                                    Utils.Toast(context,"请选择续约年限！");
//                                    return;
//                                }
//                                if (inhabitantDTO == null){
//                                    Utils.Toast(context,"请选择居民！");
//                                    return;
//                                }
//                                if (teamVo == null){
//                                    Utils.Toast(context,"请选择团队！");
//                                    return;
//                                }
//                                if (teamDoctorDTO == null){
//                                    Utils.Toast(context,"请选择团队医生！");
//                                    return;
//                                }
//
//                                ContractVo contractVo = new ContractVo();
//                                contractVo.setContractID(signDTO.getCONTRACTID());
//                                contractVo.setContractServices(signDTO.getContractServices());
//                                contractVo.setFee(signDTO.getFEE());
//                                contractVo.setSignPerson(signDTO.getSIGNPERSON());
//                                contractVo.setTeamEmpId(signDTO.getTEAM_EMP_ID());
//                                contractVo.setTags(signDTO.getTAGS());
//                                contractVo.setOtheremark(reason);
//
//                                Date date = new Date();
//                                Date endTime = Utils.getDateFromString(signDTO.getENDTIME());
//                                String signDate = Utils.getTime(date);
//                                Calendar instance = Calendar.getInstance();
//                                instance.clear();
//                                //已结束服务
//                                if (date.after(endTime)){
//                                    endTime = date;
//                                }else {
//                                    instance.setTime(endTime);
//                                    instance.add(Calendar.DAY_OF_YEAR,1);
//                                    endTime = instance.getTime();
//                                }
//
//                                Date startTime = endTime;
//                                switch (checkedButtonId){
//                                    case R.id.button1:
//                                        instance.clear();
//                                        instance.setTime(endTime);
//                                        instance.add(Calendar.MONTH,6);
//                                        endTime = instance.getTime();
//                                        break;
//                                    case R.id.button2:
//                                        instance.clear();
//                                        instance.setTime(endTime);
//                                        instance.add(Calendar.YEAR,1);
//                                        endTime = instance.getTime();
//                                        break;
//                                    case R.id.button3:
//                                        instance.clear();
//                                        instance.setTime(endTime);
//                                        instance.add(Calendar.YEAR,2);
//                                        endTime = instance.getTime();
//                                        break;
//                                    case R.id.button4:
//                                        instance.clear();
//                                        instance.setTime(endTime);
//                                        instance.add(Calendar.YEAR,3);
//                                        endTime = instance.getTime();
//                                        break;
//                                    case R.id.button5:
//                                        instance.clear();
//                                        instance.setTime(endTime);
//                                        instance.add(Calendar.YEAR,4);
//                                        endTime = instance.getTime();
//                                        break;
//                                    case R.id.button6:
//                                        instance.clear();
//                                        instance.setTime(endTime);
//                                        instance.add(Calendar.YEAR,5);
//                                        endTime = instance.getTime();
//                                        break;
//                                }
//
//                                contractVo.setSignDate(signDate);
//                                contractVo.setStartTime(Utils.getTime(startTime));
//                                contractVo.setEndTime(Utils.getTime(endTime));
//                                contractVo.setTeamID(teamVo.getTEAMID());
//                                contractVo.setPERSON_ID(inhabitantDTO.getID());
//
//                                FamilySignInterface.contract(contractVo, new WebServiceUtils.Response() {
//                                    @Override
//                                    public void onSuccess(Object result) {
//                                        Utils.Toast(context,"续约成功！");
//                                    }
//
//                                    @Override
//                                    public void onError(String error) {
//                                        Utils.Toast(context,"续约失败！\n失败原因：" + error);
//                                    }
//                                });
//
//                                show.dismiss();
//                            }
//                        });
//
//                    }else {
//                        Utils.Toast(context,"请将该签约上传云平台后再进行续约！");
//                    }
//                }else {
//                    Utils.Toast(context,"请在联网环境下或重新登录后再进行续约！");
//                }
            }
        });

        binding.button11.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //解约
//                if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                    if (StringUtils.isNotNull(signDTO.getCONTRACTID()) && !signDTO.getCONTRACTID().startsWith("@")){
//                        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
//                        View view = View.inflate(context, R.layout.termination, null);
//                        alertDialog
//                                .setView(view)
//                                .create();
//                        AlertDialog show = alertDialog.show();
//                        show.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//                        show.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//                        EditText text = show.findViewById(R.id.editText64);
//                        Button cancel = show.findViewById(R.id.button2);
//                        Button save = show.findViewById(R.id.button13);
//                        cancel.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                show.dismiss();
//                            }
//                        });
//                        save.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                String reason = text.getText().toString();
//                                saveData();
//                                signDTO.setSTATUS("5");
//                                signDTO.setUpload(false);
//                                viewModel.getSignRepository().insert(signDTO);
//                                FamilySignInterface.termination(signDTO.getCONTRACTID(), reason, new WebServiceUtils.Response() {
//                                    @Override
//                                    public void onSuccess(Object result) {
//                                        signDTO.setUpload(true);
//                                        viewModel.getSignRepository().insert(signDTO);
//                                        Utils.Toast(context,"解约成功！");
//                                    }
//
//                                    @Override
//                                    public void onError(String error) {
//                                        Utils.Toast(context,"解约失败！\n失败原因：" + error);
//                                    }
//                                });
//                                show.dismiss();
//                            }
//                        });
//                    }else {
//                        Utils.Toast(context,"请将该签约上传云平台后再进行解约！");
//                    }
//                }else {
//                    Utils.Toast(context,"请在联网环境下或重新登录后再进行解约！");
//                }
            }
        });
    }


    private void saveData(){
        signDTO.setPERSONCODE(inhabitantDTO.getCODE());
        signDTO.setPERSONID(inhabitantDTO.getID());
        signDTO.setPERSONNAME(inhabitantDTO.getNAME());
        signDTO.setPHONETEL(inhabitantDTO.getTEL());
        signDTO.setSIGNPERSON(binding.editText62.getText().toString());
        signDTO.setTEAMID(teamVo.getTEAMID());
        signDTO.setSTARTTIME(binding.textView204.getText().toString());
        signDTO.setENDTIME(binding.textView205.getText().toString());
        if (StringUtils.isNull(signDTO.getCHANNEL()))
            signDTO.setCHANNEL("APP");
        if (!"请选择人群分类".equals(binding.textView194.getText().toString()))
            signDTO.setTAGS(binding.textView194.getText().toString());
        signDTO.setTEAMNAME(teamVo.getTEAMNAME());
        signDTO.setSIGNDATE(binding.textView203.getText().toString());
        if (StringUtils.isNull(signDTO.getSTATUS()))
            signDTO.setSTATUS("2");
        signDTO.setAGE(inhabitantDTO.getAGE());
        signDTO.setCARDID(inhabitantDTO.getIDCARD());
        signDTO.setGENDER(inhabitantDTO.getSEX());
        signDTO.setFAMILYID(inhabitantDTO.getFAMILYID());
        signDTO.setOTHEREMARK(binding.editText60.getText().toString());
        signDTO.setTEAM_EMP_ID(teamDoctorDTO.getEMPLOYEEID());
        signDTO.setTEAM_EMP_NAME(teamDoctorDTO.getMEMBERNAME());
        signDTO.setFEE(binding.editText63.getText().toString());
        List<String> contractServices = new ArrayList<>();
        for (ServicePackageDTO servicePackageDTO : save) {
            contractServices.add(servicePackageDTO.getSERVICEID());
        }
        if (StringUtils.isNotNull(compressPath))
            signDTO.setATTACHFILE(compressPath);
        signDTO.setContractServices(Utils.mergeString(contractServices));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            // 图片选择结果回调
            StringBuilder builder = new StringBuilder();
            List<LocalMedia> selectListPic = PictureSelector.obtainMultipleResult(data);
            for (int i = 0; i < selectListPic.size(); i++){
                builder.append(selectListPic.get(i).getRealPath());
                if (i != selectListPic.size() - 1) {
                    builder.append(",");
                }
            }
            compressPath = builder.toString();
            Utils.loadChatImage(getActivity(),compressPath,binding.imageView5);
        }
    }

    private void setInhabitantView(){
        binding.textView177.setText(inhabitantDTO.getNAME());
        if ("1".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("男");
        else if ("2".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("女");
        binding.textView183.setText(inhabitantDTO.getTEL());
        binding.textView184.setText(inhabitantDTO.getIDCARD());
    }

    private void clearInhabitantView(){
        binding.textView177.setText("");
        binding.textView179.setText("");
        binding.textView183.setText("");
        binding.textView184.setText("");
        Utils.Toast(context,"未查到该身份证的信息，请同步居民信息后再添加！");
    }

    private void initData() {
        save = new ArrayList<>();
        Bundle arguments = getArguments();
        signDTO = (SignDTO) arguments.get("signDTO");
        servicePackageDTOS = viewModel.getServicePackageRepository().findAll();
        addSignPackageAdapter = new AddSignPackageAdapter(servicePackageDTOS);
        if (signDTO != null && StringUtils.isNotNull(signDTO.getCONTRACTID())){
            String contractId = signDTO.getCONTRACTID();
//            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                FamilySignInterface.getSignFormDetail(contractId, new WebServiceUtils.Response<Map>() {
//                    @Override
//                    public void onSuccess(Map result) {
//                        List<Map> serviceList = (List) result.get("ServiceList");
//
//                        Map contractContent = (Map) result.get("ContractContent");
//
//                        signDTO.setFEE(contractContent.get("FEE").toString());
//                        signDTO.setCHANNEL(contractContent.get("CHANNEL").toString());
//                        if (contractContent.get("OTHEREMARK") != null)
//                            signDTO.setOTHEREMARK(contractContent.get("OTHEREMARK").toString());
//                        StringBuffer contractServices = new StringBuffer();
//                        for (int i = 0; i < serviceList.size(); i++) {
//                            Map map = serviceList.get(i);
//                            String servicesId = map.get("SERVICESID").toString();
//                            if (i == serviceList.size() - 1){
//                                contractServices.append(servicesId);
//                            }else {
//                                contractServices.append(servicesId).append(",");
//                            }
//                        }
//                        signDTO.setContractServices(contractServices.toString());
//                        viewModel.getSignRepository().update(signDTO);
//                        String[] strings = Utils.divisionString(contractServices.toString());
//                        if (strings != null){
//                            List<ServicePackageDTO> d = new ArrayList<>();
//                            for (String string : strings) {
//                                ServicePackageDTO dto = viewModel.getServicePackageRepository().findByField("SERVICEID", string);
//                                if (d != null)
//                                    d.add(dto);
//                            }
//                            save = d;
//                        }
//                        initView();
//                    }
//
//                    @Override
//                    public void onError(String error) {
//                        Utils.Toast(context,"获取签约单详情失败！\n" + error);
//                    }
//                });
//            }
        }

        if (signDTO != null){
            String contractServices = signDTO.getContractServices();
            String[] strings = Utils.divisionString(contractServices);
            if (strings != null){
                List<ServicePackageDTO> dtos = new ArrayList<>();
                for (String string : strings) {
                    ServicePackageDTO dto = viewModel.getServicePackageRepository().findByField("SERVICEID", string);
                    if (dto != null)
                        dtos.add(dto);
                }
                save = dtos;
            }

//            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                FamilySignInterface.getOrgServicePack(null, 10, new WebServiceUtils.Response<List>() {
//                    @Override
//                    public void onSuccess(List result) {
//                        ServicePackageDTO[] dtos = new ServicePackageDTO[result.size()];
//                        for (int i = 0; i < result.size(); i++) {
//                            Map map = (Map) result.get(i);
//                            ServicePackageDTO packageDTO = (ServicePackageDTO) ReflectUtils.mapToObject(map, ServicePackageDTO.class);
//                            dtos[i] = packageDTO;
//                        }
//                        viewModel.getServicePackageRepository().insert(dtos);
//                        servicePackageDTOS = viewModel.getServicePackageRepository().findAll();
//                        String contractServices = signDTO.getContractServices();
//                        String[] strings = Utils.divisionString(contractServices);
//                        if (strings != null){
//                            List<ServicePackageDTO> d = new ArrayList<>();
//                            for (String string : strings) {
//                                ServicePackageDTO dto = viewModel.getServicePackageRepository().findByField("SERVICEID", string);
//                                if (d != null)
//                                    d.add(dto);
//                            }
//                            save = d;
//                            addSignPackageAdapter.setSignPackages(servicePackageDTOS);
//                            addSignPackageAdapter.setStatusTrue(save);
//                            addSignPackageAdapter.notifyDataSetChanged();
//                        }
//                    }
//                    @Override
//                    public void onError(String error) {
//                        Utils.Toast(context,"服务包更新失败！\n"+error);
//                    }
//                });
//                FamilySignInterface.getOrgServicePack(null, 11, new WebServiceUtils.Response<List>() {
//                    @Override
//                    public void onSuccess(List result) {
//                        ServicePackageDTO[] dtos = new ServicePackageDTO[result.size()];
//                        for (int i = 0; i < result.size(); i++) {
//                            Map map = (Map) result.get(i);
//                            ServicePackageDTO packageDTO = (ServicePackageDTO) ReflectUtils.mapToObject(map, ServicePackageDTO.class);
//                            dtos[i] = packageDTO;
//                        }
//                        viewModel.getServicePackageRepository().insert(dtos);
//                        servicePackageDTOS = viewModel.getServicePackageRepository().findAll();
//                        if (strings != null){
//                            List<ServicePackageDTO> d = new ArrayList<>();
//                            for (String string : strings) {
//                                ServicePackageDTO dto = viewModel.getServicePackageRepository().findByField("SERVICEID", string);
//                                if (d != null)
//                                    d.add(dto);
//                            }
//                            save = d;
//                            addSignPackageAdapter.setSignPackages(servicePackageDTOS);
//                            addSignPackageAdapter.setStatusTrue(save);
//                            addSignPackageAdapter.notifyDataSetChanged();
//                        }
//                    }
//                    @Override
//                    public void onError(String error) {
//                        Utils.Toast(context,"服务包更新失败！\n"+error);
//                    }
//                });
//            }
        }

        if (StringUtils.isNotNull(signDTO.getPERSONID())){
            inhabitantDTO = viewModel.getInhabitantRepository().findByField("ID",signDTO.getPERSONID());
//            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                InhabitantInterface.queryInhabitantBasicInfo(signDTO.getPERSONID(), 10, 0, new WebServiceUtils.Response<List>() {
//                    @Override
//                    public void onSuccess(List result) {
//                        if (result.size() == 1){
//                            Map map = (Map)result.get(0);
//                            inhabitantDTO = (InhabitantDTO) ReflectUtils.mapToObject(map, InhabitantDTO.class);
//                            viewModel.getInhabitantRepository().insert(inhabitantDTO);
//                            binding.editText2.setText(inhabitantDTO.getIDCARD());
//                            setInhabitantView();
//                        }
//                    }
//
//                    @Override
//                    public void onError(String error) {
//                        Utils.Toast(context,"获取居民信息失败！\n" + error);
//                    }
//                });
//            }
        }

        crowdLabel = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.crowd_label)));

        binding.textView194.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MultiSelectPopWindow.Builder(getActivity())
                        .setNameArray(crowdLabel)
                        .setCancelListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                signDTO.setContractServices("");
                                binding.textView194.setText("请选择人群分类");
                            }
                        })
                        .setConfirmListener(new MultiSelectPopWindow.OnConfirmClickListener() {
                            @Override
                            public void onClick(ArrayList<Integer> indexList, ArrayList<String> selectedList) {
                                if (selectedList.size() == 0){
                                    signDTO.setContractServices("");
                                    binding.textView194.setText("请选择人群分类");
                                    return;
                                }
                                String cs = Utils.mergeString(selectedList);
                                signDTO.setContractServices(cs);
                                binding.textView194.setText(cs);
                            }
                        })
                        .setCancel("取消")
                        .setConfirm("完成")
                        .setTitle("标签列表")
                        .build()
                        .show(binding.textView194);
            }
        });

        teamNames = new ArrayList<>();
        doctorNames = new ArrayList<>();
//        for (TeamVo vo : viewModel.getUserInfo().getTeamVos()) {
//            teamNames.add(vo.getTEAMNAME());
//        }
        binding.niceSpinner.attachDataSource(teamNames);

//        if (StringUtils.isNotNull(signDTO.getTEAMID())){
//            List<TeamVo> teamVos = viewModel.getUserInfo().getTeamVos();
//            for (TeamVo vo : teamVos) {
//                if (vo.getTEAMID().equals(signDTO.getTEAMID())){
//                    teamVo = vo;
//                    updateTeamDoctor();
//                    binding.niceSpinner.setSelectedIndex(teamVos.indexOf(teamVo));
//                    break;
//                }
//
//            }
//        }

        binding.niceSpinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
//                teamVo = viewModel.getUserInfo().getTeamVos().get(position);
                updateTeamDoctor();
            }
        });

        binding.niceSpinner1.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                teamDoctorDTO = teamDoctorDTOS.get(position);
            }
        });






    }


    private void updateTeamDoctor(){
        teamDoctorDTOS = viewModel.getTeamDoctorRepository().findByFieldList("TeamId",teamVo.getTEAMID());
//        if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//            FamilySignInterface.getTeamMemberInfo(teamVo.getTEAMID(), null, new WebServiceUtils.Response<List>() {
//                @Override
//                public void onSuccess(List result) {
//                    List<TeamDoctorDTO> dtos = new ArrayList<>();
//                    doctorNames.clear();
//                    for (Object o : result) {
//                        Map map = (Map) o;
//                        TeamDoctorDTO teamDoctorDTO = (TeamDoctorDTO) ReflectUtils.mapToObject(map, TeamDoctorDTO.class);
//                        doctorNames.add(teamDoctorDTO.getMEMBERNAME());
//                        dtos.add(teamDoctorDTO);
//
//                    }
//
//                    binding.niceSpinner1.attachDataSource(doctorNames);
//                    viewModel.getTeamDoctorRepository().insert(dtos.toArray(new TeamDoctorDTO[result.size()]));
//                    teamDoctorDTOS = dtos;
//                    if (StringUtils.isNotNull(signDTO.getTEAM_EMP_ID())){
//                        teamDoctorDTO = viewModel.getTeamDoctorRepository().findByField("EMPLOYEEID",signDTO.getTEAM_EMP_ID());
//                        for (int i = 0; i < teamDoctorDTOS.size(); i++) {
//                            TeamDoctorDTO teamDoctor = teamDoctorDTOS.get(i);
//                            if (teamDoctorDTO.getEMPLOYEEID().equals(teamDoctor.getEMPLOYEEID())){
//                                binding.niceSpinner1.setSelectedIndex(i);
//                                break;
//                            }
//                        }
//                    }
//                }
//
//                @Override
//                public void onError(String error) {
//                    Utils.Toast(context,"更新团队与医生数据失败！\n" + error);
//                }
//            });
//        }
        doctorNames.clear();
        for (TeamDoctorDTO doctorDTO : teamDoctorDTOS) {
            doctorNames.add(doctorDTO.getMEMBERNAME());
        }
        binding.niceSpinner1.attachDataSource(doctorNames);
        if (StringUtils.isNotNull(signDTO.getTEAM_EMP_ID())){
            teamDoctorDTO = viewModel.getTeamDoctorRepository().findByField("EMPLOYEEID",signDTO.getTEAM_EMP_ID());
            for (int i = 0; i < teamDoctorDTOS.size(); i++) {
                TeamDoctorDTO teamDoctor = teamDoctorDTOS.get(i);
                if (teamDoctorDTO.getEMPLOYEEID().equals(teamDoctor.getEMPLOYEEID())){
                    binding.niceSpinner1.setSelectedIndex(i);
                    break;
                }
            }
        }
    }

    public BigDecimal getTotal() {
        BigDecimal total = new BigDecimal("0");
        Iterator<ServicePackageDTO> iterator = save.iterator();
        while (iterator.hasNext()) {
            ServicePackageDTO next = iterator.next();
            if (next.getFEE() != null) {
                total = total.add(new BigDecimal(next.getFEE()));
            }
        }
        return total;
    }

    private void hideAddFragment() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(this);
        ft.commitAllowingStateLoss();
    }
}
